<?php

namespace app\erp\model;

use think\Model;
use traits\model\SoftDelete;
use app\erp\validate\Staffrule;
use think\Cache;

class Staffdb extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';
    protected $pk = 'member_id';
    protected $name = 'member';
    protected $type = [
        'create_time' => 'timestamp:Y-m-d H:i',
        'delete_time' => 'timestamp:Y-m-d'
    ];
    protected $autoWriteTimestamp = true;
    protected $auto = [
        'site_id',
        //'department_id'
    ];
    protected $insert = [
        'partner_id' => PARTNER_ID,
        'site_id',
        'state' => 1
    ];
    protected $append = ['contract_state'];


    // 获取所属管理员
    /*public function getBeStaffNameAttr($value, $row)
    {
        if ($row['be_staff_id']) {
            return $this->where('member_id', $row['be_staff_id'])->value('username');
        } else {
            return '';
        }
    }*/

    // 获取合同状态
    public function getContractStateAttr($value, $row)
    {
        if ($row['contract_end']) {
            if (time() > $row['contract_end']) {
                return 3;
            } else {
                return 1;
            }
        } else {
            return 2;
        }
    }

    // 获取合同开始时间
    public function getContractStartAttr($value)
    {
        return $value ? date('Y-m-d', $value) : '';
    }

    // 获取合同结束时间
    public function getContractEndAttr($value)
    {
        return $value ? date('Y-m-d', $value) : '';
    }

    // 获取所属员工
    public function setBeStaffIdAttr($value)
    {
        if (is_array($value)) {
            return implode(',', $value);
        } else {
            return '';
        }
    }

    public function getBeStaffIdAttr($value)
    {
        return explode(',', $value);
    }

    // 自动完成分站
    protected function setSiteIdAttr($value)
    {
        if (!$value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        if ($value == -1) {
            return null;
        }
        return $value;
    }

    // 自动完成部门
    protected function setDepartmentIdAttr($department_id)
    {
        if ($department_id == 0) {
            return NULL;
        } else {
            return $department_id;
        }
    }

    public $param = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr ['partner_id'] = PARTNER_ID;
        if (!isset ($new_arr ['site_id'])) {
            $new_arr ['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset ($this->param ['delete']) && $this->param ['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        $query->where('partner_id', PARTNER_ID);
        if (!empty (SITE_ID)) {
            $query->where('site_id', SITE_ID);
        }
        if (isset ($this->param ['site_id']) && !empty ($this->param ['site_id'])) {
            $query->siteId($this->param ['site_id']);
        }
        if (isset ($this->param ['username']) && !empty ($this->param ['username'])) {
            $query->username($this->param ['username']);
        }
        if (isset ($this->param ['realname']) && !empty ($this->param ['realname'])) {
            $query->realname($this->param ['realname']);
        }
        if (isset ($this->param ['member_id']) && $this->param ['member_id']) {
            $query->memberId($this->param ['member_id']);
        }
        if (isset ($this->param ['phone']) && !empty ($this->param ['phone'])) {
            $query->phone($this->param ['phone']);
        }
        if (isset ($this->param ['is_staff']) && $this->param ['is_staff'] == 'yes') {
            $query->staff();
        }
        if (isset ($this->param ['is_supplier'])) {
            $query->isSupplier($this->param ['is_supplier']);
        }
        if (isset ($this->param ['supplier_name']) && $this->param ['supplier_name']) {
            $query->supplierName($this->param ['supplier_name']);
        }
    }

    public function scopeSupplierName($query, $supplier_name)
    {
        $query->where('supplier_name', 'like', '%' . $supplier_name . '%');
    }

    public function scopeIsSupplier($query, $is_supplier)
    {
        $query->where('is_supplier', $is_supplier);
    }

    public function scopeStaff($query)
    {
        $query->where('department_id', 'EXP', 'IS NOT NULL');
    }
 public function scopeMemberId($query, $member_id)
    {
        $query->where('member_id', $member_id);
    }
    // 查询分站
    public function scopeSiteId($query, $siteId)
    {
        if ($siteId > 0) {
            $query->where('site_id', $siteId);
        } else {
            $query->where('site_id', 'EXP', 'IS NULL');
        }
    }

    // 查询用户名
    public function scopeUsername($query, $username)
    {
        $query->where('username', 'like', '%' . $username . '%');
    }

    // 查询真实姓名
    public function scopeRealname($query, $realname)
    {
        $query->where('realname', 'like', '%' . $realname . '%');
    }

    // 手机查询
    public function scopePhone($query, $phone)
    {
        $query->where('phone', 'like', '%' . $phone . '%');
    }

    /**
     *
     * @todo 获取详情
     */
    public function ajaxFind()
    {
        $data = $this->where('member_id', $this->param ['member_id'])->find();
        if ($data) {
            $data = $data->toArray();
            $data = $this->handleData($data);
        } else {
            $data = array();
        }
        return $data;
    }

    // 查询列表
    public function ajaxSelect()
    {
        $data = $this->ajaxList();
        $count = $this->ajaxCount();
        $return ['data'] = $data;
        $return ['count'] = $count;
        return $return;
    }

    public function ajaxCount()
    {
        return $this->cache($this->cache_name('staff_count'), 86400, 'staff')->count();
    }

    public function ajaxList()
    {
        $data = $this->order($this->param ['_o'], $this->param ['_b'])->page($this->param ['page'], $this->param ['limit'])->

        select();
        if (!$data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data [$key] = $this->handleData($val);
            }
        }
        return $data;
    }

    /**
     *
     * @todo 保存数据
     */
    public function ajaxSave()
    {
        $rule = new Staffrule ();

        if (isset ($this->param ['member_id']) && $this->param ['member_id'] != '') {
            if (!$rule->scene('edit')->check($this->param)) {
                return $rule->getError();
            }
            if (isset ($this->param ['password']) && $this->param ['password'] != '') {
                if (strlen(trim($this->param ['password'])) < 6) {
                    return '密码长度最少6位';
                }
                $this->param ['password'] = password($this->param ['password']);
            } else {
                unset ($this->param ['password']);
            }
            $member_id = $this->param ['member_id'];
            unset ($this->param ['member_id']);
            $this->save($this->param, [
                'member_id' => $member_id
            ]);
        } else {
            if (!$rule->check($this->param)) {
                return $rule->getError();
            }
            if (!isset ($this->param ['password']) || strlen(trim($this->param ['password'])) < 6) {
                return '密码长度最少6位，且不能为空';
            }
            $this->param ['password'] = password($this->param ['password']);
            $this->allowField(true)->save($this->param);
        }
        Cache::clear('staff');
        return 'success';
    }


    // 软删除
    public function ajaxDelete()
    {
        if (isset ($this->param ['member_id'])) {
            if (isset ($this->param ['delete']) && $this->param ['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('member_id', 'IN', $this->param ['member_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('member_id', 'IN', $this->param ['member_id']);
                }, true);
            }
            Cache::clear('staff');
        }
    }

    // 恢复数据
    public function ajaxRestore()
    {
        if (isset ($this->param ['member_id'])) {
            $map [$this->pk] = array(
                'IN',
                $this->param ['member_id']
            );
            $this->restore($map);
            Cache::clear('staff');
        }
    }

    // 数据处理
    protected function handleData($val)
    {
        $sitedb = new Sitedb ();
        $departmentdb = new Departmentdb ();
        foreach ($val as $k => $v) {
            $val [$k] = $v;
            switch ($k) {
                case 'supplier_picture':
                    if ($v) {
                        $uploaddb = new Uploaddb();
                        $val['zhang_picture_info'] = $uploaddb->getFind($v);
                    }
                    break;
                case 'member_id' :
                    $val ['staff_id'] = $v;
                    break;
                case 'site_id' :
                    $site_info = $sitedb->ajaxFind($v);
                    if (isset ($site_info ['delete_flag'])) {
                        return array();
                    } else {
                        $val ['site_id_text'] = $site_info ['site_name'];
                    }
                    if ($v == null) {
                        $val ['site_id'] = -1;
                        $val ['site_id_text'] = '主站';
                    }
                    break;
                case 'department_id' :
                    $department_info = $departmentdb->ajaxFind($v);
                    if (isset ($department_info ['delete_flag'])) {
                        return array();
                    } else {
                        $val ['department_id'] = $department_info ['department_name'];
                    }
                    break;
                case 'position' :
                    if ($v == 1) {
                        $val ['position_text'] = '站点管理员';
                    } elseif ($v == 2) {
                        $val ['position_text'] = '主管';
                    } elseif ($v == 3) {
                        $val ['position_text'] = '助理';
                    } else {
                        $val ['position_text'] = '普通职员';
                    }
                default :
                    break;
            }
        }
        return $val;
    }
}